import React, { Component, Fragment } from 'react';
import { Form, Modal, message } from 'antd';
import StepContentBottom from './StepContentBottom';
import { connect } from 'dva';
import LoginWrapper from '@/components/LoginWrapper';

const { PasswordFormItem } = LoginWrapper;

@connect(({ loading: { models: { resetPassword } }, resetPassword: { information } }) => ({
  loading: !!resetPassword,
  information,
}))
@Form.create()
class StepThird extends Component {
  handleSubmit = e => {
    e.preventDefault();
    const {
      form: { validateFields },
      dispatch,
      information,
      history,
    } = this.props;
    validateFields((err, fieldsValue) => {
      if (!err) {
        let values = {
          password: fieldsValue.password,
          code: information.code,
        };
        let typeAction, fieldName;
        if (information.type === 'mobile') {
          typeAction = 'resetPassword/setPasswordByMobile';
          fieldName = 'mobile';
        }
        if (information.type === 'mail') {
          typeAction = 'resetPassword/setPasswordByMail';
          fieldName = 'mail';
        }

        dispatch({
          type: typeAction,
          payload: {
            ...values,
            [fieldName]: information.account,
          },
        })
          .then(() => {
            history.push('/user/resetPassword/result');
          })
          .catch(errMsg => {
            message.error(errMsg);
          });
      }
    });
  };

  onSuccess() {
    const { history } = this.props;
    const modal = Modal.success({
      title: '更改成功',
      content: '点击确定后您会返回登录页面',
      onOk() {
        modal.destroy();
        history.push('/user/login');
      },
    });
  }

  render() {
    const { form, loading } = this.props;
    return (
      <Fragment>
        <Form onSubmit={this.handleSubmit} className="step-content-second">
          <PasswordFormItem confirm form={form} placeholder="密码包括6-16位大小写字母数字" />
          <StepContentBottom loading={loading} buttonText="提交" />
        </Form>
      </Fragment>
    );
  }
}

export default StepThird;
